package edu.biwu.request;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;

/**
 * HttpServletRequest中获取请求体的方法:
 *    public String getParameter(String name):适用于一个参数对应一个值,后端根据前端name的值获取对应的值
 *    public String[] getParameterValues(String name):使用于一个参数对应多个值,后端根据前端的name的值获取该参数对应的所有值
 *    public String[] getParameterValues(String name):将页面提交的所有参数封装到一个Map中,Map中数据的格式
 *                                                    key:提交的name值
 *                                                    value:name对应一个或多个值,将这些值放到一个字符串数组中
 */
@WebServlet("/req/demo03")
public class RequestDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //利用getParameter()获取参数对应的单一值
        //例如: username=abc&password=123456&gender=female
        System.out.println(request.getParameter("username"));
        System.out.println(request.getParameter("password"));
        System.out.println(request.getParameter("gender"));

        //利用getParameterValues()获取爱好
        //hobby=basketball&hobby=swimming
        //String[] hobbies = request.getParameterValues("hobby");
        //for (String hobby : hobbies) {
        //    System.out.println(hobby);
        //}
        Stream.of(request.getParameterValues("hobby")).forEach(System.out::println);

        System.out.println("-------------------------------------------------------");
        //username=abc&password=123456&gender=female&hobby=badminton&hobby=basketball&hobby=swimming&province=hubei&city=jingzhou&text=++++++++++++++++abcd%0D%0A++++++++++++&hid=abc
        //Map<String, String[]> parameterMap = request.getParameterMap();
        //for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
        //    System.out.println(entry.getKey() + "=" + Arrays.toString(entry.getValue()));
        //}
        request.getParameterMap().forEach((key, value) -> System.out.println(key + "=" + Arrays.toString(value)));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doGet(request,response);
    }
}
